<template>
  <div class="MultiAttributeTable">
    <div v-for="(item, index) in AttributeList" :key="index" class="mb-5">
      <template v-if="item.show != false">
        <div class="flex justify-between items-center">
          <div class="flex">
            <div class="flex items-center border rounded">
              <div style="color: #3487ff; min-width: 80px; padding-left: 10px">
                {{ item.group_name }}
              </div>
              <el-input
                class="input-border"
                v-model.trim="item.valueName"
                placeholder="输入后按回车添加中文规格值名"
                @keyup.enter="addSpecification(index, item.valueName)"
              ></el-input>
            </div>
          </div>
          <div class="flex items-center">
            <el-checkbox
              v-model="item.is_relation_img"
              @change="changeRelation($event, index)"
              :true-label="1"
              :false-label="0"
              label="是否关联属性图片"
              size="large"
            />
            <el-button
              class="ml-4"
              type="primary"
              :loading="item.loading"
              @click="translate(index, item.values)"
              >一键翻译</el-button
            >
          </div>
        </div>
        <div class="flex border-t border-l border-r justify-start">
          <div class="border-r category">
            <div class="borHeader w-full h-12 text-center leading-10">类目</div>
            <div class="inputStyle border-b index-bgColor">规格名称</div>
            <div
              class="inputStyle border-b"
              v-for="(tab, t) in item.values[0].language_values"
              :key="t"
            >
              规格值名
            </div>
          </div>
          <div class="flex-auto flex w-full">
            <template v-for="(tab, t) in item.values" :key="t">
              <Item
                class="flex-auto"
                v-model="item.values[t]"
                @translate="translateOne($event, index, item.values)"
                v-if="tab.show"
              ></Item>
            </template>
          </div>
          <div class="w-16 border-l operate">
            <div class="borHeader w-full h-12 text-center leading-10">操作</div>
            <div class="inputStyle border-b index-bgColor"></div>
            <div
              class="inputStyle border-b"
              v-for="(del, d) in item.values[0]?.language_values"
              :key="del"
            >
              <el-button type="danger" link @click="handelDel(index, d, del)"
                >删除</el-button
              >
            </div>
          </div>
        </div>
      </template>
    </div>
  </div>
</template>
<script setup name="MultiAttributeTable">
import { translationBatch } from "@/api/index";
import { ElMessage } from "element-plus";
import Item from "./Item";
import { reactive, inject, watch, nextTick } from "vue";
import useCommonStore from "@/store/modules/common";
import { storeToRefs } from "pinia";
const commonStore = useCommonStore();
const { languageOptions } = storeToRefs(commonStore);

const emit = defineEmits(["update:modelValue"]);
let formData = reactive(inject("form"));
const props = defineProps({
  modelValue: {
    type: Object,
    default: () => {},
  },
  languages: {
    type: Array,
    default: () => [],
  },
});
const languageList = computed({
  get: () => props.languages,
  set: (val) => {
    emit("update:modelValue", val);
  },
});
const AttributeList = computed({
  get: () => props.modelValue,
  set: (val) => {
    emit("update:modelValue", val);
  },
});
// 添加属性值名
const addSpecification = (index, valueName) => {
  if (!valueName) return ElMessage.error("请输入属性值名称");

  const flag = AttributeList.value[index].values[0].language_values.some((i) => {
    return i.value.toUpperCase() == valueName.toUpperCase();
  });
  if (flag) {
    ElMessage.error("该规格值已存在，不允许重复添加！");
    return;
  }

  AttributeList.value[index].values.forEach((item, index) => {
    if (index === 0) {
      item.language_values.push({
        language_id: item.language_id,
        group: 1,
        spu_id: formData.value.spu,
        name: "规格值名",
        value: valueName,
      });
    } else {
      item.language_values.push({
        language_id: item.language_id,
        group: 1,
        spu_id: formData.value.spu,
        name: valueName,
        value: "",
      });
    }
  });
  AttributeList.value[index].valueName = "";
};
// 删除
const handelDel = (index, d, item) => {
  if (formData.value.dev_status >= 4 && item.id) {
    ElMessage.error("当前状态不允许删除");
    return;
  }
  AttributeList.value[index].values.forEach((item) => {
    item.language_values.splice(d, 1);
  });
};

// 一键翻译
const translate = async (index, values) => {
  AttributeList.value[index].loading = true;
  let arr = [];
  let specificationName = [];

  let list = values.filter((item) => item.language_id == 1);
  list &&
    list[0].language_values.forEach((item) => {
      arr.push(item.value);
    });
  specificationName.push(list[0].name);

  let target_lang = [];
  languageOptions.value.forEach((o) => {
    languageList.value.forEach((lang) => {
      if (o.id === lang) {
        target_lang.push(o.short_name);
      }
    });
  });

  let languageArr = ["en"].concat(target_lang);

  let texts = {};
  let specifications = {};
  languageArr.forEach((i) => {
    texts[i] = arr;
    specifications[i] = specificationName;
  });

  // 翻译规格值名
  let param = {
    texts,
    use_proxy: true,
  };
  await translationBatch(param)
    .then((res) => {
      values.forEach((att, index) => {
        att.language_values.forEach((item, i) => {
          if (res.data[att["language_code"]] && res.data[att["language_code"]].length) {
            item.value = res.data[att["language_code"]][i];
          }
        });
      });
    })
    .finally(() => {
      AttributeList.value[index].loading = false;
    });

  // 翻译规格名称
  let specificationParam = {
    texts: specifications,
    use_proxy: true,
  };
  await translationBatch(specificationParam)
    .then((res) => {
      values.forEach((att) => {
        if (res.data[att["language_code"]] && res.data[att["language_code"]].length) {
          att.name = res.data[att["language_code"]][0];
        }
      });
      ElMessage.success("翻译成功!");
    })
    .finally(() => {
      AttributeList.value[index].loading = false;
    });
};
const translateOne = (language_code, index, values) => {
  let arr = [];
  let specificationName = [];

  let list = values.filter((item) => item.language_id == 1);
  list &&
    list[0].language_values.forEach((item) => {
      arr.push(item.value);
    });
  specificationName.push(list[0].name);

  let param = {
    texts: {
      [language_code]: arr,
    },
    use_proxy: true,
  };
  translationBatch(param)
    .then((res) => {
      values.forEach((att) => {
        att.language_values.forEach((item, i) => {
          if (res.data[att["language_code"]] && res.data[att["language_code"]].length) {
            item.value = res.data[att["language_code"]][i];
          }
        });
      });
    })
    .finally(() => {});

  let specificationParam = {
    texts: {
      [language_code]: specificationName,
    },
    use_proxy: true,
  };
  translationBatch(specificationParam)
    .then((res) => {
      values.forEach((att, index) => {
        if (res.data[att["language_code"]] && res.data[att["language_code"]].length) {
          att.name = res.data[att["language_code"]][0];
        }
      });
      ElMessage.success("翻译成功!");
    })
    .finally(() => {
      AttributeList.value[index].loading = false;
    });
};

const changeRelation = (val, index) => {
  AttributeList.value.forEach((item, i) => {
    if (index == i && val) {
      item.is_relation_img = val;
    } else {
      item.is_relation_img = 0;
    }
  });
};
const createSKU = inject("createSKU");
//判断createSKU和AttributeList是否有值
watch(
  [createSKU, AttributeList],
  async (val) => {
    nextTick(() => {
      if (createSKU.value == "createSKU" && AttributeList.value.length) {
        for (let i = 0; i < AttributeList.value.length; i++) {
          translateOne("en", i, AttributeList.value[i].values);
        }
      }
    }, 1000);
  },
  {
    immediate: true,
  }
);
</script>

<style lang="scss" scoped>
.borHeader {
  background: #f6faff;
  box-shadow: 0px 1px 0px 0px #e6e7e9;
  .operate {
    position: fixed;
    right: 0;
    top: 0;
  }
}

.inputStyle {
  height: 49px;
  line-height: 49px;
  width: 100%;
  text-align: center;
}

.category {
  width: 100px;
}

.index-bgColor {
  background-color: #fef6e7;
}

.input-border {
  width: 220px;
  :deep(.el-input__wrapper) {
    border: none !important;
    box-shadow: none !important;
    padding: 0px; //前边边距去掉
  }
}
</style>
